/**
 * Created by 13576 on 2017/11/22.
 * 为了0416迭代上线，重构此文件
 */
import React from 'react';
import {connect} from 'react-redux';
import {Form, Switch, Icon, Input, Button, Row, Col, message} from 'antd';
import Chooser from 'components/chooser';
import companyMaintainService from 'containers/enterprise-manage/company-maintain/company-maintain.service';
import Selector from 'components/selector';
import {deepCopy, messages} from "share/common";
const FormItem = Form.Item;

class WrappedNewBankAccount extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      companyInfo:{},
      bankObj: {
        bank: [],//这个字段只是用来显示，可以不传给后端，
        bankName: "",

        countryCode: "",//银行国家code：根据银行来显示
        country: "",//国家名称：根据银行来显示
        accountOpening: "",//开户地：根据银行来显示
        accountOpeningAddress: "",//银行详细地址：根据银行来显示
        swiftCode: "",//开户支行Swift：：根据银行来显示

        bankAccountName: "",//银行账户名称
        bankAccountNumber: "",//银行账户账号
        accountCode: "",//账户账号
        currencyCode: "",//币种
        remark: "",//备注
        enabled: true,//状态
      },
      bankCode: '',
      bankInfo: {}
    };
  }


  componentDidMount() {
    //根据公司oid获取公司详细信息--包含账套信息
    companyMaintainService.getCompanyInfo(this.props.params.companyOId)
      .then(res=>{
        this.setState({
          companyInfo: res.data
        })
      });
    if (this.props.params.flag === 'create') {
      //新增
    } else {
      //更新
      companyMaintainService.getCompanyBankInfoById(this.props.params.flag)
        .then((res) => {
          let bankObj = deepCopy(res.data);
          let _bank = deepCopy(res.data);
          // countryName 要注意接口的坑，前端上传的时候与解析的时候，要转换
          // openAccount 要注意接口的坑，前端上传的时候与解析的时候，要转换
          bankObj.bank = [
            {
              bankType: _bank.bankType,
              bankCode: _bank.bankCode,
              bankTypeBankCode:_bank.bankType + _bank.bankCode,
              bankBranchName: _bank.bankBranchName,
              bankName: _bank.bankName,
              city: _bank.city,
              cityCode: _bank.cityCode,
              province: _bank.province,
              provinceCode: _bank.provinceCode,
              countryCode: _bank.countryCode,
              countryName: _bank.country,
              country: _bank.country,
              bankAddress: _bank.accountOpeningAddress,
              accountOpeningAddress:_bank.accountOpeningAddress,
              detailAddress:_bank.accountOpeningAddress,
              swiftCode : _bank.swiftCode,
              openAccount: _bank.bankAddress
            }
          ];
          this.setState({bankObj})
        })
    }
  }

  //保存新建公司
  handleSave = (e) => {
    e.preventDefault();
    let {bankObj} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.companyId = this.props.params.companyId;
        values.bankCode = values.bank[0].bankCode;
        values.bankBranchName = values.bank[0].bankBranchName;
        values.bankKey = values.bank[0].bankCode;
        values.bankName = values.bank[0].bankName;
        values.city = values.bank[0].city;
        values.bankType = values.bank[0].bankType;
        values.cityCode = values.bank[0].cityCode;
        values.province = values.bank[0].province;
        values.provinceCode = values.bank[0].provinceCode;
        values.countryCode = values.bank[0].countryCode;
        if (bankObj.id) {
          //编辑时，传id
          values.id = bankObj.id
        }
        this.addOrUpdateBankAccount(values)
      }
    })

  };

  //更新或者创建银行账户
  addOrUpdateBankAccount = (bankAccount) => {
    //todo
    //这个接口一定要重构，一来是抛错信息，二来是前端只需要传银行代码
    //还有改为创建是post,编辑是put,现在都是post
    this.setState({loading: true});
    companyMaintainService.addOrUpdateBankAccount(bankAccount)
      .then(res => {
        this.setState({loading: false});
        //保存成功或者更新成功
        message.success(messages("common.operate.success"));
        this.setState({loading: false});
        this.context.router.goBack();
      })
  }

  //取消就直接返回
  handleCancel = () => {
    this.context.router.goBack();
  };

  /*
  * todo
  * 公司关联银行
  * 期望后端只需要前端传一个银行代码就可以了
  * */
  handleBankCodeChange = (e) => {
    //选择银行之后，国家，开户地，银行详细地址，swiftCode显示出来
    let {bankObj} = this.state;
    if (e.length > 0) {
      let bank = e[0];
      Object.assign(bankObj, {
        bankType: bank.bankType,
        countryCode: bank.countryCode,
        country: bank.countryName,

        bankAddress: bank.openAccount,
        accountOpeningAddress:  bank.detailAddress,
        swiftCode: bank.swiftCode,
        bankTypeBankCode: bank.bankType+bank.bankCode,
      });
    } else {
      Object.assign(bankObj, {
        countryCode: "",
        country: "",
        bankAddress: "",

        accountOpeningAddress:  "",
        swiftCode: "",
        bankTypeBankCode: "",
      });
    }
    this.setState({
      loading: false,
      bankObj
    })
  }
  //监听表单值
  handleChange = (e) => {
    if (this.state.loading) {
      this.setState({
        loading: false,
      })
    }
  };

  //状态
  switchCardStatusChange = (e) => {
    let {bankObj} = this.state;
    bankObj.enabled = e;
    this.setState({
      loading: false,
      bankObj
    })
  };

  render() {
    const {bankObj, loading} = this.state;
    const {getFieldDecorator} = this.props.form;

    let params = {
      tenantId:this.state.companyInfo.tenantId,
      setOfBooksId:this.state.companyInfo.setOfBooksId,
      enable:true
      // language: 'chineseName',
    };
    return (
      <Form className="ant-advanced-search-form"
            onSubmit={this.handleSave}
            onChange={this.handleChange}>

        <Row gutter={24}>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key3'/*银行名称*/)}//银行名称
              colon={true}>
              {getFieldDecorator('bank', {
                initialValue: bankObj.bank,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.select")
                  },
                ]
              })(
                <Chooser single={true}
                         type="select_bank"
                         value={bankObj.bank}
                         placeholder={messages("common.please.select")}
                         labelKey="bankBranchName"
                         onChange={this.handleBankCodeChange}
                         valueKey="bankTypeBankCode"
                         listExtraParams={{}}/>
              )
              }
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key5'/*国家*/)} /* 国家*/
              colon={true}>
              {getFieldDecorator('country', {
                initialValue: bankObj.country,
                rules: []
              })(
                <Input disabled={true}
                       value={bankObj.country}
                       placeholder={messages('enterprise-manage.key46'/*根据银行自动生成*/)}

                />
              )
              }
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key6'/*开户地*/)} /* 开户地*/
              colon={true}>
              {getFieldDecorator('bankAddress', {
                initialValue: bankObj.bankAddress,
              })(
                <Input disabled={true}
                       value={bankObj.bankAddress}
                       placeholder={messages('enterprise-manage.key46'/*根据银行自动生成*/)}

                />
              )
              }
            </FormItem>

          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key7'/*银行详细地址*/)}  /* 银行详细地址*/
              colon={true}>
              {getFieldDecorator('accountOpeningAddress', {
                initialValue: bankObj.accountOpeningAddress,
                rules: []
              })(
                <Input disabled={true}
                       value={bankObj.accountOpeningAddress}
                       placeholder={messages('enterprise-manage.key46'/*根据银行自动生成*/)}

                />
              )
              }
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key10'/*开户支行Swift Code*/)}  /* 开户支行Swift Code*/
              colon={true}>
              {getFieldDecorator('swiftCode', {
                initialValue: bankObj.swiftCode,
                rules: []
              })(
                <Input disabled={true}
                       value={bankObj.swiftCode}
                       placeholder={messages('enterprise-manage.key46'/*根据银行自动生成*/)}
                />
              )
              }
            </FormItem>
          </Col>

          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key9'/*银行账户账号*/)}//银行账户账号
              colon={true}>
              {getFieldDecorator("bankAccountNumber", {
                initialValue: bankObj.bankAccountNumber,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  },
                  {
                    message: messages('enterprise-manage.key47'/*只能是数字与-*/),//"只能是数字与-",
                    validator: (rule, value, cb) => {
                      if (value === null || value === undefined || value === "") {
                        cb();
                        return;
                      }
                      let regExp = /^[0-9\- ]+$/i;
                      //去掉空格
                      value = value.replace(/ /g, '');
                      if (value.length <= 30 && regExp.test(value)) {
                        cb();
                      } else {
                        cb(false);
                      }
                    },
                  },
                  {
                    max: 30,
                    message: messages('enterprise-manage.key48'/*不能超过30个字符*/)                  },
                ]
              })
              (
                <Input placeholder={messages("common.please.enter")}/>
              )
              }
            </FormItem>
          </Col>

        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key8'/*银行账户名称*/)} /* 银行账户名称*/
              colon={true}>
              {getFieldDecorator('bankAccountName', {
                initialValue: bankObj.bankAccountName,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  },
                  {
                    max: 30,
                    message: messages('enterprise-manage.key48'/*不能超过30个字符*/)                  },
                ]
              })(
                <Input placeholder={messages("common.please.enter")}/>
              )
              }
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key49'/*账户代码*/)} /* 账户代码*/
              colon={true}>
              {getFieldDecorator('accountCode', {
                initialValue: bankObj.accountCode,
                rules: [
                  {
                    max: 35,
                    message: messages('enterprise-manage.key50'/*不能超过35个字符*/)                  },
                  {
                    message: messages('enterprise-manage.key51'/*只能是数字与字母*/),//只能输入数字与字母
                    validator: (rule, value, cb) => {
                      if (value === null || value === undefined || value === "") {
                        cb();
                        return;
                      }
                      let regExp = /^[a-z0-9]+$/i;
                      //去掉空格
                      value = value.replace(/ /g, '');
                      if (value.length <= 35 && regExp.test(value)) {
                        cb();
                      } else {
                        cb(false);
                      }
                    },
                  },
                ]
              })(
                <Input placeholder={messages("common.please.enter")}/>
              )
              }
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key52'/*币种*/)}//币种
              colon={true}>
              {getFieldDecorator("currencyCode", {
                initialValue: bankObj.currencyCode,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.select")
                  },
                ]
              })
              (

                <Selector type={'currency_for_company'} params={params} filter={item => item.enable}
                          showSearch={true}
                          placeholder={messages("common.please.select")}
                          allowClear={false}
                         />

              )
              }
            </FormItem>
          </Col>

        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key11'/*备注*/)}  /* 备注*/
              colon={true}>
              {getFieldDecorator('remark', {
                initialValue: bankObj.remark,
                rules: [
                  {
                    max: 100,
                    message: messages('enterprise-manage.key53'/*不能超过100个字符*/)                  },
                ]
              })(
                <Input placeholder={messages("common.please.enter")}/>
              )
              }
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem
              label={messages('enterprise-manage.key54'/*状态*/)} /* 状态*/
              colon={true}>
              {getFieldDecorator('enabled', {
                initialValue: bankObj.enabled
              })(
                <Switch
                  defaultChecked={bankObj.enabled}
                  checked={bankObj.enabled}
                  checkedChildren={<Icon type="check"/>}
                  onChange={this.switchCardStatusChange}
                  unCheckedChildren={<Icon type="cross"/>}/>
              )
              }
            </FormItem>
          </Col>
        </Row>
        <div>
          <Button type="primary"
                  loading={loading}
                  htmlType="submit">
            {messages("common.save") /*保存*/}
          </Button>
          <Button onClick={this.handleCancel}
                  style={{marginLeft: 8}}>
            {messages("common.cancel") /*取消*/}
          </Button>
        </div>

      </Form>
    )
  }

}

function mapStateToProps(state) {
  return {}
}

WrappedNewBankAccount.contextTypes = {
  router: React.PropTypes.object
};

const NewBankAccount = Form.create()(WrappedNewBankAccount);

export default connect(mapStateToProps)(NewBankAccount);
